package com.pn.taikao.service.impl;

import com.pn.taikao.entity.Answer;
import com.pn.taikao.entity.Score;
import com.pn.taikao.mapper.AnswerMapper;
import com.pn.taikao.mapper.ScoreMapper;
import com.pn.taikao.service.ScoreService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ScoreServiceImpl implements ScoreService {

    private final ScoreMapper scoreMapper;
    private final AnswerMapper answerMapper;

    public ScoreServiceImpl(ScoreMapper scoreMapper, AnswerMapper answerMapper) {
        this.scoreMapper = scoreMapper;
        this.answerMapper = answerMapper;
    }

    @Override
    @Transactional
    public void saveOrUpdate(Long examId, BigDecimal totalScore) {
        Score existingScore = scoreMapper.selectByExamId(examId);
        LocalDateTime now = LocalDateTime.now();
        
        if (existingScore != null) {
            existingScore.setTotalScore(totalScore);
            existingScore.setUpdateTime(now);
            scoreMapper.update(existingScore);
        } else {
            Score score = new Score();
            score.setExamId(examId);
            score.setTotalScore(totalScore);
            score.setCreateBy("system");
            score.setCreateTime(now);
            score.setUpdateTime(now);
            scoreMapper.insert(score);
        }
    }

    @Override
    public Score getByExamId(Long examId) {
        return scoreMapper.selectByExamId(examId);
    }

    @Override
    @Transactional
    public void calculateAndSaveTotalScore(Long examId) {
        List<Answer> answers = answerMapper.selectByExamId(examId);
        BigDecimal totalScore = BigDecimal.ZERO;
        
        for (Answer answer : answers) {
            if (answer.getScore() != null) {
                totalScore = totalScore.add(answer.getScore());
            }
        }
        
        saveOrUpdate(examId, totalScore);
    }

    @Override
    public List<Score> getByStudentId(Long studentId) {
        return scoreMapper.selectByStudentId(studentId);
    }

    @Override
    public List<Map<String, Object>> getStatisticsByPaperId(Long paperId, Long teacherId) {
        return scoreMapper.selectStatisticsByPaperId(paperId, teacherId);
    }

    @Override
    public List<Map<String, Object>> getAllStatistics(Long teacherId) {
        return scoreMapper.selectAllStatistics(teacherId);
    }
}

